<template>
    <div class="data-reference-dialog">
        <el-dialog :title="modelName + ' ' + $t('tool.modelManage.dataReference')" :visible.sync="dialogFormVisible"
            width="85vw" :close-on-click-modal="false" :destroy-on-close="false">
            <splitpanes horizontal :dbl-click-splitter="false" class="default-theme" style="height: 700px;">
                <pane>
                    <div class="data-reference flex flex-row">
                        <div class="data-reference-left-tree flex flex-col">
                            <div class="data-reference-tree-title flex justify-center items-center"
                                style="height: 32px">
                                可引用类别
                            </div>
                            <div class="data-reference-tree-box flex" style="height: calc(100% - 32px)">
                                <Tree :treeData="ownTreeData" @nodeClick="nodeClick" :draggable="false">
                                </Tree>
                            </div>
                        </div>
                        <div class="data-reference-center-tree flex flex-col">
                            <div class="data-reference-tree-title flex justify-center items-center">
                                可引用数据
                            </div>
                            <div style="height: calc(100% - 35px);overflow-y: auto;">
                                <div class="main-version-select flex items-center">
                                    {{ $t("tool.modelManage.mainVersionSelect") }}：
                                    <el-select v-model="selectedMainVersionId" style="width: calc(100% - 80px)"
                                        class="jtyj-select" @change="handleChangeMainVersion">
                                        <el-option v-for="item in mainVersionOptions" :key="item.mainVersionId"
                                            :label="item.mainVersionName" :value="item.mainVersionId">
                                        </el-option>
                                    </el-select>
                                </div>
                                <div class="data-reference-tree-box flex">
                                    <Tree ref="modelDataTreeRef" :isGeneralFolderAndFile="true" :showMenu="false"
                                        :defaultExpandedKeys="defaultExpandedKeys" :treeData="modelDataList"
                                        @nodeClick="handleNodeClick" :draggable="false"></Tree>
                                </div>
                            </div>
                        </div>
                        <div class="data-reference-right-box flex flex-col">
                            <div class="model-jsonschema-display">
                                <FolderDetail v-if="isFolder" ref="folderRef" :flag="'dataModeling'"
                                    :nodeInfo="selectedModelData"></FolderDetail>
                                <template v-if="isFile">
                                    <div class="form-wrap flex flex-col" v-if="selectedModelData">
                                        <div class="flex flex-row w-full" style="justify-content: space-between">
                                            <el-input v-model="selectedModelData.data.modelDataName"
                                                readOnly></el-input>
                                            <div class="actions-wrap">
                                                <el-button @click="handleAddReference">{{
                                                    $t("tool.modelManage.addReference")
                                                    }}</el-button>
                                            </div>
                                        </div>
                                        <div class="model-detail">
                                            {{ selectedModelData.data.modelDataDescription }}
                                        </div>
                                    </div>
                                    <div class="form-jsonSchema">
                                        <JsonSchema
                                            v-if="selectedModelData && selectedModelData.data.jsonSchemaData != null"
                                            ref="jsonSchemaRef" :currentName="$t('tool.modelManage.rootNode')"
                                            :currentSchema.sync="selectedModelData.data.jsonSchemaData"
                                            :parentSchema.sync="selectedModelData.data.jsonSchemaData" :currentIndex="1"
                                            :writable="true" :isReadonly="true"></JsonSchema>
                                    </div>

                                </template>
                            </div>
                        </div>
                    </div>
                </pane>
                <pane size="28" min-size="28" max-size="100">
                    <div style="width: 100%; height: 1px;"></div>
                    <DataReferencePaper v-if="referenceList.length > 0" :referenceList="referenceList"
                        @nodeRemove="handelPaperNodeRemove"></DataReferencePaper>
                </pane>

            </splitpanes>
        </el-dialog>
    </div>
</template>

<script>
import {
    getSelfModelTree,
    getMainVersionList,
    getModelDataTree,
    getQuoteList,
    addQuote,
    deleteQuote
} from "@/api/myspace/model-manage-tool/model-manage";
import { mapState } from "vuex";
import Tree from "@/components/LeftTree/tree.vue";
import JsonSchema from "./gradient.vue";
import FolderDetail from "./folder-detail.vue";
import DataReferencePaper from "./data-reference-paper.vue";
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
export default {
    props: {
        modelId:{
            type: Number,
            default: 0
        },
        modelName:{
            type: String,
            default: ''
        },
        mainVersionId:{
            type: Number,
            default: 0
        }
    },
    data() {
        return {
            selectedNodeInfo: null, // 当前选中的树节点信息
            selectedMainVersionId: null, // 当前选中的主版本id
            selectedModelDataId: null, // 当前选中的数据结构id
            selectedModelData: null, // 当前选中的数据结构
            dialogFormVisible: false,
            isFolder: false, // 是否是文件夹
            isFile: false, // 是否是文件
            ownTreeData: [], // 本账户模型列表
            mainVersionOptions: [], // 版本列表
            modelDataList: [], // 数据结构列表
            referenceList: [], // 引用列表
            defaultExpandedKeys: [], // 默认展开的节点
        };
    },
    components: {
        Tree,
        JsonSchema,
        FolderDetail,
        DataReferencePaper,
        Splitpanes,
        Pane
    },
    computed: {
        ...mapState({
            right_menuList: (state) => state.modelManageTool.right_menuList,
            userId: (state) => state.user.id,
        }),
    },
    created() {
    },
    methods: {
        init() {
            this.dialogFormVisible = true;
            this.reset();
            this.getList();
            this.getReferenceList();
        },
        reset() {
            this.selectedMainVersionId = null;
            this.selectedModelData = null;
            this.mainVersionOptions = [];
            this.modelDataList = [];
            this.isFolder = false;
            this.isFile = false;
        },
        // 获取模型树
        getList() {
            getSelfModelTree().then((res) => {
                if (res.code == 200 && Array.isArray(res.data)) {
                    this.ownTreeData = res.data[0].commonTreeList;
                }
            });
        },
        // 获取版本列表
        getMainVersionList(node) {
            getMainVersionList({
                modelId: node.modelId,
            }).then((response) => {
                if (response.code == 200) {
                    this.mainVersionOptions = response.rows;
                    if (this.mainVersionOptions.length > 0) {
                        this.selectedMainVersionId = this.mainVersionOptions[0].mainVersionId;
                        this.getModelData(this.selectedMainVersionId);
                    }
                }
            });
        },

        // 获取模型和主版本唯一决定的数据结构列表
        getModelData(mainVersion) {
            getModelDataTree({
                modelId: this.selectedNodeInfo.data.modelId,
                mainVersion: mainVersion,
            }).then((response) => {
                if (response.code == 200) {
                    this.modelDataList = response.data[0].commonTreeList;
                    // 默认选中并展开第一个节点
                    if (this.modelDataList.length > 0) {
                        localStorage.setItem("currentSelectedQuoteData", JSON.stringify(this.modelDataList))
                        this.defaultExpandedKeys = [this.modelDataList[0].id];
                        this.$nextTick(() => {
                            this.$refs.modelDataTreeRef.$refs.treeRef.setCurrentKey(this.modelDataList[0].id)
                        })
                        this.handleNodeClick(this.modelDataList[0])
                    }
                }
            });
        },
        // 获取引用列表
        getReferenceList() {
            getQuoteList({
                quoteModelId: this.modelId, //引用的模型 ID
                quoteMainVersionId: this.mainVersionId, //引用的主版本 ID
                userId: this.userId
            }).then(response => {
                if (response.code == 200) {
                    this.referenceList = response.rows;
                }
            })
        },

        // 树节点点击事件
        nodeClick(nodeData) {
            this.selectedNodeInfo = nodeData;
            this.reset();
            this.getMainVersionList(nodeData.data);
        },
        // 主版本改变以后
        handleChangeMainVersion(val) {
            this.selectedModelData = null;
            this.getModelData(val);
        },
        // 选择的数据结构发生变化
        handleNodeClick(node) {
            this.selectedModelData = node;
            this.isFolder = node.data.nodeType == 0;
            this.isFile = node.data.nodeType == 1;
            if (node.data.jsonSchemaData == null) return;
            if (typeof node.data.jsonSchemaData == "string") {
                this.selectedModelData.data.jsonSchemaData = JSON.parse(
                    node.data.jsonSchemaData
                );
            }
        },
        // 添加引用
        handleAddReference() {
            addQuote({
                quoteModelId: this.modelId, //引用的模型 ID
                quoteMainVersionId: this.mainVersionId, //引用的主版本 ID
                beQuoteModelId: this.selectedNodeInfo.id, //被引用的模型ID
                beQuoteModelDataId: this.selectedModelData.data.modelDataId, //被引用的模型数据 ID
                beQuoteMainVersionId: this.selectedMainVersionId, //被引用的主版本 ID
                userId: this.userId, //创建人ID
            }).then(response => {
                if (response.code == 200) {
                    this.getReferenceList();
                }
            })
        },

        // 处理图节点删除（删除引用）
        handelPaperNodeRemove(dataQuoteId){ 
            deleteQuote(dataQuoteId).then(response => {
                if (response.code == 200) {
                    this.getReferenceList();
                    this.$modal.msgSuccess("删除成功");
                }
            })
        },
    },
};
</script>

<style lang="scss" scoped>
.data-reference-dialog {
    .data-reference {
        width: 100%;
        height: 500px;

        .data-reference-left-tree,
        .data-reference-center-tree {
            height: 100%;
            display: flex;
            flex-direction: column;
            border-right: 1px solid var(--ui-border-color-split);
            box-sizing: border-box;

            .data-reference-tree-title {
                height: 35px;
                font-weight: 600;
                letter-spacing: 2px;
            }

            .main-version-select {
                height: 45px;
            }

            .data-reference-tree-box {
                flex-grow: 1;
                padding-right: 5px;
            }
        }

        .data-reference-left-tree {
            width: 230px;
        }

        .data-reference-center-tree {
            width: 240px;
            padding: 0 5px;
            box-sizing: border-box;
            overflow-x: hidden;
        }

        .data-reference-right-box {
            width: calc(100% - 230px - 240px);
            padding-left: 5px;
            box-sizing: border-box;

            .model-jsonschema-display {
                height: 100%;
                display: flex;
                flex-direction: column;

                .form-wrap {
                    .title-compose {
                        height: 32px;
                        font-weight: 600;
                        white-space: nowrap;
                        text-overflow: ellipsis;
                        flex: 1;
                        padding: 0;
                        font-size: 23px;
                        line-height: 32px;
                        overflow: hidden;
                        border-bottom: 2px solid var(--ui-border-color-split);
                        box-sizing: border-box;
                        cursor: text;
                    }

                    .actions-wrap {
                        margin-left: 16px;
                        gap: 8px;
                        display: inline-flex;
                        align-items: center;
                    }

                    .model-detail {
                        margin-top: 6px;
                        border-bottom: 1px solid var(--ui-border-color-split);
                        height: 22px;
                        font-size: var(--ui-font-size-base);
                    }
                }

                .form-jsonSchema {
                    border: 1px solid var(--ui-border-color-split);
                    border-radius: 6px;
                    padding: 5px;
                    margin-top: 5px;
                    box-sizing: border-box;
                    flex-grow: 1;
                    overflow: auto;
                }
            }
        }
    }
}
</style>